package com.pfdu.simplescheduler.repo;

import com.pfdu.simplescheduler.config.SimpleSchedulerConfig;
import com.pfdu.simplescheduler.node.AppNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

@Slf4j
@Component
public class NodeRepo {
    @Autowired
    @Qualifier(value = "SimpleSchedulerJdbcTemplate")
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private SimpleSchedulerConfig config;

    private String table;

    @PostConstruct
    public void init() {
        this.table = config.getNodeTable();
    }

    /**
     * @param heartBeatInterval 心跳间隔
     * @return 获取可用节点列表
     */
    @Cacheable(cacheNames = "live-node")
    public List<AppNode> listAvailable(int heartBeatInterval) {
        StringBuilder sql = new StringBuilder();
        sql.append("select serial_no AS serialNo")
                .append(" from ")
                .append(table)
                .append(" where last_heart_beat_time > (SYSDATE-NUMTODSINTERVAL(?, 'second'))");
        return jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper(AppNode.class), heartBeatInterval * 3);
    }

    public int maxSerialNo() {
        StringBuilder sql = new StringBuilder();
        sql.append("select max(serial_no) from ").append(table);
        Integer max = jdbcTemplate.queryForObject(sql.toString(), Integer.class);
        return max == null ? 0 : max;
    }

    public int insert(int maxSerialNo) {
        StringBuilder sql = new StringBuilder();
        sql.append("insert into " + table + "(serial_no, last_heart_beat_time)")
                .append(" values(?, SYSDATE)");
        return jdbcTemplate.update(sql.toString(), maxSerialNo);
    }

    public void updateHeartBeatTime(int serialNo) {
        StringBuilder sql = new StringBuilder();
        sql.append("update ").append(table)
                .append(" set last_heart_beat_time = SYSDATE")
                .append(" where serial_no = ?");
        jdbcTemplate.update(sql.toString(), serialNo);
    }

}
